package cn.cloudtogo.server;

import cn.cloudtogo.common.atomapi.token.ApiTokenProperties;
import cn.cloudtogo.common.atomapi.token.ApiTokenService;
import cn.cloudtogo.common.model.ApiTokenDao;
import cn.cloudtogo.common.model.ExternalDatasourceDao;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration(proxyBeanMethods = false)
public class WebMvcConfiguration implements WebMvcConfigurer {

    private final ExternalDatasourceDao datasourceDao;
    private final ApiTokenService apiTokenService;
    private final ApiTokenDao apiTokenDao;
    private final ApiTokenProperties properties;

    public WebMvcConfiguration(ExternalDatasourceDao datasourceDao,
                               ApiTokenDao apiTokenDao,
                               ApiTokenService apiTokenService,
                               ApiTokenProperties properties) {
        this.datasourceDao = datasourceDao;
        this.apiTokenDao = apiTokenDao;
        this.apiTokenService = apiTokenService;
        this.properties = properties;
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new RequestHeaderObjectArgumentResolver(datasourceDao));
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (!properties.isEnabled()) {
            return;
        }
        registry.addInterceptor(new ApiTokenInterceptor(apiTokenService, apiTokenDao));
    }
}
